<template>
  <div>
    当前的cId为:{{ cagegoryId }},当前选中的文章状态为：{{ state }}
    <el-row style="margin-bottom: 5px">
      <el-col :span="4">
        <el-input v-model="para.keyword" placeholder="请输入关键字"></el-input>
      </el-col>
      <el-col :span="20">
        <el-button type="primary" icon="el-icon-search" @click="handleSearch"
          >搜索</el-button
        >
        <el-button type="success" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="handleDelMultiple">批量删除</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table
          :data="articles"
          highlight-current-row
          @selection-change="selsChange"
          @current-change="selectCurrentRow"
          v-loading="listLoading"
          row-key="aId"
          border
          style="width: 100%"
          ref="table"
        >
          <el-table-column type="selection" width></el-table-column>
          <el-table-column
            type="index"
            width="50"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template scope="scope">
              <el-dropdown size="small">
                <el-button
                  size="small"
                  type="primary"
                  @click="handleEdit(scope.$index, scope.row)"
                  >编辑<i class="el-icon-arrow-down el-icon--right"></i
                ></el-button>
                <el-dropdown-menu slot="dropdown" style="max-width: 90px">
                  <el-dropdown-item style="padding-left: 0%">
                    <el-button
                      type="danger"
                      size="small"
                      style="min-width: 90px"
                      @click="handleDel(scope.$index, scope.row)"
                      >删除</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item style="padding-left: 0%">
                    <el-button
                      type="success"
                      size="small"
                      style="min-width: 90px"
                      v-if="scope.row.aStatus !== 4"
                      @click="handlePassStatus(scope.$index, scope.row)"
                      >审核通过</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item style="padding-left: 0%">
                    <el-button
                      type="warning"
                      size="small"
                      style="min-width: 90px"
                      v-if="scope.row.aStatus === 4"
                      @click="handleCancelPassStatus(scope.$index, scope.row)"
                      >取消审核</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item style="padding-left: 0%">
                    <el-button
                      type="text"
                      size="small"
                      style="min-width: 90px"
                      v-if="scope.row.aStatus !== 0"
                      @click="handleChangeToDraft(scope.$index, scope.row)"
                      >转为草稿</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item style="padding-left: 0%">
                    <el-button
                      type="info"
                      size="small"
                      style="min-width: 90px"
                      v-if="scope.row.aStatus !== 1"
                      @click="handleChangeToPendingReview(scope.$index, scope.row)"
                      >转为待审核</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item style="padding-left: 0%">
                    <el-button
                      type="text"
                      size="small"
                      style="min-width: 90px"
                      v-if="scope.row.aStatus !== 2"
                      @click="handleChangeToFirstPass(scope.$index, scope.row)"
                      >转为一审</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item style="padding-left: 0%">
                    <el-button
                      type="info"
                      size="small"
                      style="min-width: 90px"
                      v-if="scope.row.aStatus !== 3"
                      @click="handleChangeToSecondPass(scope.$index, scope.row)"
                      >转为二审</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item style="padding-left: 0%">
                    <el-button
                      type="plain"
                      size="small"
                      style="min-width: 90px"
                      @click="handleAddToCategory(scope.$index, scope.row)"
                      >添加到专题</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item style="padding-left: 0%">
                    <el-button
                      type="info"
                      size="small"
                      style="min-width: 90px"
                      @click="handleShowArticleDetail(scope.$index, scope.row)"
                      >预览</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="aId"
            label="ID"
            width="100"
            align="center"
          ></el-table-column> -->
          <el-table-column label="文章标题" width="300">
            <template slot-scope="scope">
              <!-- <i class="fa" :class="scope.row.Icon"></i> -->
              {{ scope.row.aTitle }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="aDescribe"
            label="简介"
            width
          ></el-table-column> -->
          <el-table-column
            prop="aAuthorName"
            label="作者"
            width="140"
            align="center"
          ></el-table-column>
          <!-- <el-table-column
            prop="aComeFrom"
            label="作者"
            width="150"
            align="center"
          ></el-table-column> -->
          <el-table-column
            prop="aVisitCount"
            label="点击数"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="aWeight"
            label="权重"
            align="center"
            width="60"
          ></el-table-column>
          <el-table-column
            prop="aEditorRealName"
            label="编辑"
            width="140"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="aStatus"
            label="状态"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              {{ formartStatus(scope.row.aStatus) }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="aUpdateTime"
            label="更新时间"
            width
          ></el-table-column> -->
          <!-- <el-table-column prop="PnameArr" label="父节点" width="" sortable>
      </el-table-column>-->
          <!-- <el-table-column prop="Code" label="路由地址" width ></el-table-column>
      <el-table-column prop="MName" label="API接口" width ></el-table-column>
      <el-table-column prop="OrderSort" label="Sort" width ></el-table-column>
      <el-table-column prop="IsButton" label="是否按钮" width="100" >
        <template slot-scope="scope">
          <el-tag
            :type="!scope.row.IsButton  ? 'success' : 'danger'"
            disable-transitions
          >{{!scope.row.IsButton ? "否":"是"}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="Func" label="按钮事件" width ></el-table-column>
      <el-table-column prop="IsHide" label="是否隐藏" width="100" >
        <template slot-scope="scope">
          <el-tag
            :type="!scope.row.IsHide  ? 'success' : 'danger'"
            disable-transitions
          >{{!scope.row.IsHide ? "否":"是"}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="IskeepAlive" label="keepAlive" width="100" >
        <template slot-scope="scope">
          <el-tag
            :type="!scope.row.IskeepAlive  ? 'success' : 'danger'"
            disable-transitions
          >{{!scope.row.IskeepAlive ? "否":"是"}}</el-tag>
        </template>
      </el-table-column> -->
          <!-- <el-table-column label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
      </el-table-column>-->
        </el-table>
      </el-col>
    </el-row>
    <el-row justify="center" type="flex" style="margin-top: 5px">
      <el-col :span="12">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="para.pageIndex"
          :page-sizes="[10, 20, 40, 100]"
          :page-size="para.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-col>
    </el-row>

    <!-- 文章详情对话框 -->
    <el-dialog
      title="文章详情"
      :visible.sync="articleDetailDialogVisible"
      width="80%"
      :before-close="handleCloseArticleDetailDialog"
    >
      <el-row type="flex" justify="center" :gutter="20">
        <el-col :span="6">
          <article-picture-card
            :article="articleSeleted"
          ></article-picture-card>
        </el-col>
        <el-col :span="18">
          <el-container style="height: 500px; border: 1px solid #eee">
            <Article :article="articleSeleted"></Article>
          </el-container>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 添加到新的分类对话框 -->
    <el-dialog
      title="添加到新的分类"
      :visible.sync="articleAddToNewCategoryDialogVisible"
      width="60%"
      :before-close="handleCloseArticleAddToNewCategoryDialog"
    >
    <el-row type="flex"  :gutter="2">
        <el-col :span="10">
          <el-cascader
           placeholder="请选择，支持搜索功能，默认为根节点分支"
           style="min-width: 400px"
           v-model="PidArr"
           :options="options"
           filterable
           :props="{ checkStrictly: true, expandTrigger: 'hover' }"
           :key="iscascaderShow"
          ></el-cascader>
        </el-col>
        <!-- 添加按钮 -->
        <el-col :span="2">
          <el-button type="success" icon="el-icon-check" circle></el-button>
        </el-col>
      </el-row>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseArticleAddToNewCategoryDialog">取 消</el-button>
        <el-button type="primary" @click="addToNewCategorySubmit"
          >确 定</el-button
        >
      </span>
      <!-- <el-row type="flex" justify="center" :gutter="20">
        <el-col :span="6">
          <article-picture-card
            :article="articleSeleted"
          ></article-picture-card>
        </el-col>
        <el-col :span="18">
          <el-container style="height: 500px; border: 1px solid #eee">
            <Article :article="articleSeleted"></Article>
          </el-container>
        </el-col>
      </el-row> -->
    </el-dialog>
    <!-- 文章添加对话框 -->
    <el-dialog
      title="添加文章"
      :visible.sync="articleAddDialogVisible"
      width="80%"
      :before-close="handleCloseArticleAddDialog"
    >
      <el-row type="flex" justify="center" :gutter="20">
        <el-col :span="24">
          <article-add
            :cId="cagegoryId"
            @addArticle="handelAddSuccess"
          ></article-add>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getArticleListPage,
        getCategoriesByArticleId,
        removeArticle,
        removeArticleMultiple,
        // changeArticleStatus,
        changeArticleStatusToFinalPass,
        changeArticleStatusToReject,
        changeArticleStatusToDraft,
        changeArticleStatusToPendingReview,
        changeArticleStatusToFirstPass,
        changeArticleStatusToSecondPass,

        getCategoryTree,
        GetCategoryTreeById
       } from "@/api/api";
import ArticlePictureCard from "./ArticlePictureCard.vue";
import Article from "@/components/Article/Article.vue";
import ArticleAdd from "./Article/ArticleAdd.vue";
export default {
  components: { ArticlePictureCard, Article, ArticleAdd },
  data() {
    return {
      //   table相关
      listLoading: false,
      //   article相关
      para: {
        pageIndex: 1,
        pageSize: 10,
        keyword: "",
        state: "all",
        cId: 0,
      },
      articles: [],
      articleSeleted: {},
      total: 0,
      sels:[],//表格多选存储内容

      // 文章详情对话框
      articleDetailDialogVisible: false,
      // 添加文章对话框
      articleAddDialogVisible: false,
      //添加分类对话框
      articleAddToNewCategoryDialogVisible: false,
      currentSelectedArticleIdForAddToNewCategoryDialog:0,//当前选中的文章Id

      options: [], //用于在级联选择分类时存放数据
      PidArr: [],
      aExtraCategoryId: [], //要添加到的其他分类数组id
      iscascaderShow: 0,  //用于避免Cannot read properties of null (reading 'level')报错
    };
  },
  props: ["cagegoryId", "state"],
  methods: {
    handleEdit() {},
    handleDel(index,row) {
      // console.log(index);
      // console.log(row);
      // 执行删除请求,成功后在数据中清除指定行内容
      let para={
        aId:row.aId
      }
      removeArticle(para).then(res=>{
        if(res.data.response){
          //删除成功
          this.articles.splice(index,1);
          this.$message.success("操作成功!");
        }
        else{
          this.$message.error("服务器错误,操作失败!");
        }
      }).catch(err=>{
        this.$message.error(`服务器${err}错误,操作失败!`);
      });
    },
    formartStatus(val) {
      let label = "";
      switch (val) {
        case 0:
          label = "草稿";
          break;
        case 1:
          label = "待审核的稿件";
          break;
        case 2:
          label = "一审通过";
          break;
        case 3:
          label = "二审通过";
          break;
        case 4:
          label = "终审通过";
          break;
        case 5:
          label = "退稿";
          break;
      }
      return label;
    },
    getArticles() {
      this.listLoading = true;
      getArticleListPage(this.para).then((res) => {
        this.articles = res.data.response.data;
        this.total = res.data.response.dataCount;
        this.listLoading = false;
        // console.log(this.articles);
      });
    },
    handleSearch() {
      // this.$message.info("search");
      this.getArticles();
    },

    handleDelMultiple() {
      var count=this.sels.length;
      let aIds=[];
      // this.$message.info("delMultiple");
      this.$alert(`确定同时删除${count}条内容吗?`, '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.sels.forEach(item=>{
              aIds.push(item.aId);
            });
            let data={
              aIds:aIds
            }
            // console.log(data);
            removeArticleMultiple(aIds).then(res=>{
              if(res.data.response){
                this.$message.success("操作成功!");
                this.getArticles();
              }
              else{
                this.$message.error("操作失败!");
              }
            });
          }
        });
    },
    handlePassStatus(index,data){
      // console.log(index);console.log(data);
      this.$alert(`确定通过此条内容吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText:'取消',
          callback: action => {
            //默认此项操作将文章直接变为终审通过状态
            let para={
              id:data.aId
              // status:4
            }
            changeArticleStatusToFinalPass(para).then(res=>{
              // console.log(res);
              if(res.data.success){
                this.$message.success("操作成功!");
                this.getArticles();
              }
              else{
                this.$message.error("操作失败!");
              }
            });
          }
        });

    },
    // 取消审核=退稿
    handleCancelPassStatus(index,data){
      this.$alert(`确定退稿此条内容吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText:'取消',
          callback: action => {
            //默认此项操作将文章直接变为退稿状态
            let para={
              id:data.aId
              // status:5
            }
            changeArticleStatusToReject(para).then(res=>{
              // console.log(res);
              if(res.data.success){
                this.$message.success("操作成功!");
                this.getArticles();
              }
              else{
                this.$message.error("操作失败!");
              }
            });
          }
        });
    },
    // 草稿
    handleChangeToDraft(index,data){
      this.$alert(`确定将此条内容变为草稿吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText:'取消',
          callback: action => {
            let para={
              id:data.aId
              // status:5
            }
            changeArticleStatusToDraft(para).then(res=>{
              // console.log(res);
              if(res.data.success){
                this.$message.success("操作成功!");
                this.getArticles();
              }
              else{
                this.$message.error("操作失败!");
              }
            });
          }
        });
    },
    // 待审核
    handleChangeToPendingReview(index,data){
      this.$alert(`确定将此条内容转为待审核吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText:'取消',
          callback: action => {
            let para={
              id:data.aId
              // status:5
            }
            changeArticleStatusToPendingReview(para).then(res=>{
              // console.log(res);
              if(res.data.success){
                this.$message.success("操作成功!");
                this.getArticles();
              }
              else{
                this.$message.error("操作失败!");
              }
            });
          }
        });
    },
    // 一审
    handleChangeToFirstPass(index,data){
      this.$alert(`确定将此条内容转为一审状态吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText:'取消',
          callback: action => {
            let para={
              id:data.aId
              // status:5
            }
            changeArticleStatusToFirstPass(para).then(res=>{
              // console.log(res);
              if(res.data.success){
                this.$message.success("操作成功!");
                this.getArticles();
              }
              else{
                this.$message.error("操作失败!");
              }
            });
          }
        });
    },
    // 二审
    handleChangeToSecondPass(index,data){
      this.$alert(`确定将此条内容转为二审状态吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText:'取消',
          callback: action => {
            let para={
              id:data.aId
            }
            changeArticleStatusToSecondPass(para).then(res=>{
              // console.log(res);
              if(res.data.success){
                this.$message.success("操作成功!");
                this.getArticles();
              }
              else{
                this.$message.error("操作失败!");
              }
            });
          }
        });
    },

    // 添加到新的分类
    handleAddToCategory(index,data){
      // =========渲染数据===========
      let para = { pid: 0 };
      // 使用之前先清空
      this.options = [];
      // this.ArticleAddform.PidArr=[];此时不用清空，可以用来定位原数据
      getCategoryTree(para).then((res) => {
        ++this.iscascaderShow;
        this.options.push(res.data.response);
      });
      // =========渲染数据结束===========
        this.articleAddToNewCategoryDialogVisible=true;
        this.currentSelectedArticleIdForAddToNewCategoryDialog=data.aId;
        console.log(this.currentSelectedArticleIdForAddToNewCategoryDialog);
    },
    handleCloseArticleAddToNewCategoryDialog(){
        this.articleAddToNewCategoryDialogVisible=false;
        this.currentSelectedArticleIdForAddToNewCategoryDialog=0;
    },
    addToNewCategorySubmit(){ //只能一个一个加
        // 如果是添加Category
        // 先拿到此文章对应的分类集合
        let alreadyAmountCategories=[];
        // setTimeout(() => {
        //   // 此处如果不加延时，那么alreadyAmountCategories会一直为空
          
        // }, 500);
        // 拿到PidArr的最后一项就是用户选中的数据id
        let count = this.PidArr.length;
        // 将新的Category信息存到数组中
        var category = {};
        category.cId = this.PidArr[count - 1];
        if (category.cId === 0) {
          this.$message.error("不要在根节点下添加内容");
          return;
        }
        let isAlreadyInArr = false;
        getCategoriesByArticleId(this.currentSelectedArticleIdForAddToNewCategoryDialog).then(res=>{
            // console.log(res);
            if(res.data.success){
              // this.$message.success("操作成功!");
              console.log(res.data.response);
              alreadyAmountCategories=res.data.response;//此处只能用=赋值！！！
              // console.log(alreadyAmountCategories);
              // this.getArticles();
              // console.log(alreadyAmountCategories);
              // console.log(category);
              // for (let index = 0; index < alreadyAmountCategories.length; index++) {
              //   console.log('foreach');
              //   if (alreadyAmountCategories[index].cID === category.cId) {
              //     isAlreadyInArr = true;
              //   }
                
              // }
              alreadyAmountCategories.forEach(function (item, index, arr) {
                // console.log('foreach');
                if (item.cID === category.cId) {
                  isAlreadyInArr = true;
                }
              });
            }
            else{
              this.$message.info("此条目没有绑定到任何节点!");
            }
            if (isAlreadyInArr) {
              this.$message.error("不要重复添加相同的分类");
              return;
            }
          });
        
        
        
        // if (category.cId == this.currentSelectedArticleIdForAddToNewCategoryDialog) {
        //   this.$message.error("不要重复添加相同的分类");
        //   return;
        // }
        
        
        
    //     var promise =  GetCategoryTreeById(category.cId);
    //     category.cTree = promise.data.response;
    //     this.extraCategories.push(category);
    },

    // Page method
    handleSizeChange(val) {
      this.para.pageSize = val;
      this.getArticles();
    },
    handleCurrentChange(val) {
      this.para.pageIndex = val;
      this.getArticles();
    },

    // table method
    selsChange(val) {
      // console.log(val);
      this.sels=val;
    },
    // 用于单选，val表示用户单击选中行的数据
    selectCurrentRow(val) {
      // console.log(val);
      // this.articleSeleted = val;
    },

    // article dialog
    handleShowArticleDetail(index, row) {
      //  console.log(index);
      //  console.log(row);
      this.articleSeleted = row;
      this.articleDetailDialogVisible = true;
    },
    handleCloseArticleDetailDialog() {
      this.articleDetailDialogVisible = false;
    },

    // article add dialog
    handleAdd() {
      // this.$message.info("add");
      this.articleAddDialogVisible = true;
    },
    handleCloseArticleAddDialog() {
      this.articleAddDialogVisible = false;
    },
    handelAddSuccess(val) {
      this.$message.info(val);
      console.log(val);
      this.getArticles();
      this.articleAddDialogVisible=false;
    },

    
  },
  mounted() {
    // this.getArticles(); //获取文章
  },
  watch: {
    //监听categoryId变化，如果变化，就将值传给cId，同时更新数据
    cagegoryId(val) {
      // this.$message.info(old);
      this.para.cId = val;
      // this.getArticles();
    },
    //监听state变化，如果变化，就将值传给state，同时更新数据
    state(val) {
      // this.$message.info(old);
      this.para.state = val;
      // this.getArticles();
    },
  },
};
</script>